package org.apache.dubbo.common.io;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class UnsafeByteArrayOutputStream extends OutputStream {

    protected byte[] buffer;

    protected int count;

    public UnsafeByteArrayOutputStream() {
        this(32);
    }

    public UnsafeByteArrayOutputStream(int size) {
        if (size < 0) {
            throw new IllegalArgumentException("Negative initial size: " + size);
        }
        buffer = new byte[size];
    }

    @Override
    public void write(int b) throws IOException {
        int newCount = count + 1;
        if (newCount > buffer.length) {
            buffer = Bytes.copyOf(buffer,Math.max(buffer.length << 1,newCount));
        }
        buffer[count] = (byte) b;
        count = newCount;
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        }
        if (len == 0) {
            return;
        }
        int newCount = count + len;
        if (newCount > buffer.length) {
            buffer = Bytes.copyOf(buffer,Math.max(buffer.length << 1,newCount));
        }
        System.arraycopy(b,off,buffer,count,len);
        count = newCount;
    }

    public int size() {
        return count;
    }

    public void reset() {
        count = 0;
    }

    public byte[] toByteArray() {
        return Bytes.copyOf(buffer,count);
    }

    public ByteBuffer toByteBuffer() {
        return ByteBuffer.wrap(buffer,0,count);
    }

    public void writeTo(OutputStream out) throws IOException {
        out.write(buffer,0,count);
    }

    @Override
    public String toString() {
        return new String(buffer, 0, count);
    }

    public String toString(String charset) throws UnsupportedEncodingException {
        return new String(buffer, 0, count, charset);
    }

    @Override
    public void close() throws IOException {
    }
}
